# backend/video_analysis.py
"""
视频分析服务模块
支持视频+文本输入，文本输出的多模态分析
"""

import os
import base64
import json
import time
import requests
import re
from datetime import datetime
from typing import Dict, Any, Optional, List
from fastapi import HTTPException

# 视频分析API配置
VIDEO_API_URL = "http://localhost:8020/analyze_video"  # 您的视频模型API地址
VIDEO_API_KEY = "your_video_api_key"  # 您的API密钥

# 测试模式配置
TEST_MODE = False  # 设置为True时使用模拟响应，False时使用真实API

class VideoAnalyzer:
    def __init__(self):
        self.video_info = {
            "filename": "未知视频",
            "size": 0,
            "duration": 0,
            "format": "未知格式"
        }
    
    def preprocess_video(self, video_path: str) -> str:
        """视频预处理"""
        try:
            # 获取视频基本信息
            import subprocess
            
            # 使用ffprobe获取视频信息（需要安装ffmpeg）
            try:
                result = subprocess.run([
                    'ffprobe', '-v', 'quiet', '-print_format', 'json', 
                    '-show_format', '-show_streams', video_path
                ], capture_output=True, text=True, timeout=30)
                
                if result.returncode == 0:
                    video_data = json.loads(result.stdout)
                    format_info = video_data.get('format', {})
                    streams = video_data.get('streams', [])
                    
                    # 提取视频信息
                    self.video_info.update({
                        "filename": os.path.basename(video_path),
                        "size": int(format_info.get('size', 0)),
                        "duration": float(format_info.get('duration', 0)),
                        "format": format_info.get('format_name', '未知格式')
                    })
                    
                    # 查找视频流
                    video_stream = next((s for s in streams if s.get('codec_type') == 'video'), None)
                    if video_stream:
                        self.video_info.update({
                            "width": video_stream.get('width', 0),
                            "height": video_stream.get('height', 0),
                            "fps": eval(video_stream.get('r_frame_rate', '0/1'))
                        })
                        
            except (subprocess.TimeoutExpired, FileNotFoundError, json.JSONDecodeError):
                # 如果ffprobe不可用，使用文件信息
                self.video_info.update({
                    "filename": os.path.basename(video_path),
                    "size": os.path.getsize(video_path)
                })
            
            return video_path
            
        except Exception as e:
            raise HTTPException(status_code=400, detail=f"视频预处理失败: {str(e)}")
    
    def call_video_api(self, video_path: str, prompt: str, chat_history: List[Dict[str, str]] = None, *, temperature: float = 0.8, top_p: float = 0.4, max_tokens: int = 1024) -> str:
        """调用视频分析API - 支持多轮对话"""
        try:
            print(f"开始调用视频分析API，视频路径: {video_path}")
            
            # 读取视频文件
            with open(video_path, "rb") as video_file:
                video_base64 = base64.b64encode(video_file.read()).decode('utf-8')
            
            # 构建消息列表，支持多轮对话
            messages = []
            
            # 添加历史对话
            if chat_history:
                for msg in chat_history:
                    messages.append({
                        "role": msg.get("role", "user"),
                        "content": msg.get("content", "")
                    })
            
            # 添加当前用户消息
            messages.append({"role": "user", "content": prompt})
            
            # 构建请求
            payload = {
                "video": video_base64,  # 直接传base64
                "messages": messages,  # 支持多轮对话的消息列表
                "num_frames": -1,  # -1=自动（1fps），推荐！
                "max_frames": 64,
                "temperature": float(temperature),
                "top_p": float(top_p),
                "max_tokens": int(max_tokens)
            }
            
            response = requests.post("http://10.143.12.79:8192/v1/chat", json=payload, timeout=180)
            # response = requests.post("http://127.0.0.1:8192/v1/chat", json=payload, timeout=180)
            
            print(f"API响应状态码: {response.status_code}")
            
            if response.status_code == 200:
                result = response.json()
                print("API调用成功")
                return result.get("response", "分析完成")
            else:
                error_msg = f"""
                API请求失败！
                状态码：{response.status_code}
                错误信息：{response.text}
                可能原因：
                1. API密钥无效或过期
                2. 视频模型服务未启动
                3. 请求参数不符合要求
                4. 视频文件格式不支持
                """
                print(f"API调用失败: {error_msg}")
                return error_msg

        except requests.exceptions.Timeout:
            error_msg = "API调用超时，请检查网络连接"
            print(error_msg)
            return error_msg
        except requests.exceptions.ConnectionError:
            error_msg = "网络连接错误，无法连接到视频分析API"
            print(error_msg)
            return error_msg
        except Exception as e:
            error_msg = f"API调用异常：{str(e)}"
            print(error_msg)
            return error_msg
    
    
    def sanitize_response(self, response: str) -> str:
        """清洗和格式化响应内容"""
        text = str(response)
        
        # 清理特殊字符和格式符号
        text = re.sub(r'\*{5,}', '', text)
        text = re.sub(r'\[\{\{\'text\': \'###.*?\}\}', '', text)
        text = re.sub(r'\'\}\}\]', '', text)
        text = re.sub(r'\bv[nm]\b', '', text)
        text = re.sub(r'\u3000', ' ', text)
        text = text.replace('\\n', '\n')
        
        # 结构化格式优化
        text = re.sub(r'【(.*?)】', r'\n## \1\n', text)
        text = re.sub(r'\*{3,}(\d+\.)', r'\n\1', text)
        text = re.sub(r'(\d+\.)([^\n])', r'\1 \2', text)
        
        # 转义特殊字符
        text = text.replace("{", "{{").replace("}", "}}")
        text = text.replace("data:video/", "data-video-")
        
        # 智能分段处理
        text = '\n'.join([line.strip() for line in text.split('\n') if line.strip()])
        
        return text[:3000]  # 限制长度
    
    def format_analysis(self, text: str) -> str:
        """二次结构化处理"""
        text = re.sub(r'(\d+\.\s*)([^\n]+)', r'- \2\n', text)
        text = re.sub(r'\n##', r'\n\n##', text)
        text = re.sub(r'\n{3,}', r'\n\n', text)
        return text
    
    def analyze_video(self, video_path: str, custom_prompt: str = None) -> Dict[str, Any]:
        """视频分析主函数"""
        try:
            # 预处理视频
            processed_video = self.preprocess_video(video_path)
            
            # 构建分析提示词
            if custom_prompt:
                analysis_prompt = custom_prompt
            else:
                analysis_prompt = "请分析这个视频的内容"
            
            # 调用API进行分析
            raw_result = self.call_video_api(processed_video, analysis_prompt)
            
            # 清洗和格式化结果
            clean_result = self.format_analysis(self.sanitize_response(raw_result))
            
            return {
                "success": True,
                "analysis_result": clean_result,
                "timestamp": datetime.now().isoformat(),
                "video_info": self.video_info.copy()
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }
    
    def analyze_video_complete(self, video_path: str, input_text: str = None, 
                              chat_history: List[Dict[str, str]] = None,
                              temperature: float = 0.8, top_p: float = 0.4, max_tokens: int = 1024) -> Dict[str, Any]:
        """完整的视频分析 - 支持多轮对话"""
        try:
            # 预处理视频
            processed_video = self.preprocess_video(video_path)
            
            # 构建分析提示词
            if input_text and input_text.strip():
                # 使用用户输入的提示词
                analysis_prompt = input_text
            else:
                # 使用默认提示词
                analysis_prompt = "请分析这个视频的内容"
            
            # 调用API进行分析，传入对话历史
            raw_result = self.call_video_api(processed_video, analysis_prompt, chat_history, temperature=temperature, top_p=top_p, max_tokens=max_tokens)
            
            # 清洗和格式化结果
            clean_result = self.format_analysis(self.sanitize_response(raw_result))
            return {
                "success": True,
                "analysis_result": clean_result,
                "timestamp": datetime.now().isoformat(),
                "video_info": self.video_info.copy()
            }
            
        except Exception as e:
            return {
                "success": False,
                "error": str(e),
                "timestamp": datetime.now().isoformat()
            }
    

# 创建全局分析器实例
video_analyzer = VideoAnalyzer()
